//
//  KLApplyKeysMsgTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/9/28.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLApplyKeysMsgTableViewController.h"
#import "KLHelp.h"
#import "KLHttpAPI.h"
#import "GUAAlertView.h"
#import "HemaConst.h"
#import "HemaFunction.h"
#import "SSKeychain.h"
#import "Masonry.h"
#import "BuleFuction.h"
#import "UIActionSheet+Blocks.h"
#import "NSData+hex.h"
#import "NSString+Hex.h"
#import "MJRefresh.h"

@interface KLApplyKeysMsgTableViewController ()<UIActionSheetDelegate>
@property (nonatomic,strong) NSArray *allMessageInfor; //所有收到的消息字典
@end

@implementation KLApplyKeysMsgTableViewController
-(NSArray *)allMessageInfor{
    if(!_allMessageInfor){
        _allMessageInfor = [NSArray array];
    }
    return _allMessageInfor;
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.tableView.mj_header endRefreshing];
}

-(void)viewDidAppear:(BOOL)animated{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshMessageList];
    }];
    [self.tableView.mj_header beginRefreshing];
    [self.tabBarItem setBadgeValue:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(17, 0, UI_View_Width, 60)];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 1, UI_View_Width, 0.3)];
    line.alpha = 0.6;
    line.backgroundColor = [UIColor lightGrayColor];
    [self.tableView.tableFooterView addSubview:line];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.allMessageInfor.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"applyKeysMst"];
    if(!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"applyKeysMst"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
        cell.userInteractionEnabled = YES;
    }
    cell.accessoryType = UITableViewCellAccessoryDetailButton;
    NSDictionary *singleMessage = self.allMessageInfor[indexPath.row];
    NSString *type = [singleMessage objectForKey:@"type"];
    
    //左上角小图标
    UIImageView *icon = [[UIImageView alloc]init];
    if(type.integerValue == 0){
        icon.image = [UIImage imageNamed:@"系统消息"];
    }else{
        icon.image = [UIImage imageNamed:@"钥匙-线"];
    }
    [cell.contentView addSubview:icon];
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(10);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
    }];
    //小红点
    NSString *status = [singleMessage objectForKey:@"status"];
    if(status.integerValue == 0){
        UIImageView *redPoint = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"红点图标"]];
        redPoint.layer.masksToBounds = YES;
        redPoint.layer.cornerRadius = 4;
        [cell.contentView addSubview:redPoint];
        [redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(8);
            make.width.mas_equalTo(8);
            make.top.equalTo(icon).with.offset(0);
            make.right.equalTo(icon).with.offset(0);
        }];
    }
    //申请人的Label
    UILabel *applyPersonLabel = [[UILabel alloc]init];
    applyPersonLabel.text = [NSString stringWithFormat:@"%@(%@)  预付:%@元",[singleMessage objectForKey:@"nickname"],[singleMessage objectForKey:@"applymobile"],[singleMessage objectForKey:@"single_price"]];
    applyPersonLabel.font = [UIFont systemFontOfSize:16];
    applyPersonLabel.textColor = RGB_UI_COLOR(90, 90, 90);
    [cell.contentView addSubview:applyPersonLabel];
    [applyPersonLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.left.equalTo(icon).with.offset(40);
    }];
    //锁名
    UILabel *lockNameLabel = [[UILabel alloc]init];
    if(type.integerValue == 0){
        lockNameLabel.text = [NSString stringWithFormat:@"锁名: %@",[singleMessage objectForKey:@"name"]];
    }else{
        lockNameLabel.text = [NSString stringWithFormat:@"钥匙串名: %@",[singleMessage objectForKey:@"name"]];
    }
    lockNameLabel.font = [UIFont systemFontOfSize:14];
    lockNameLabel.textColor = [UIColor lightGrayColor];
    [cell.contentView addSubview:lockNameLabel];
    [lockNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(applyPersonLabel).with.offset(21);
        make.left.equalTo(icon).with.offset(40);
    }];
    //有效期
    UILabel *dateLabel = [[UILabel alloc]init];
    dateLabel.numberOfLines = 2;
    dateLabel.text = [NSString stringWithFormat:@"有效期: %@ \n至 %@",[singleMessage objectForKey:@"startdate"],[singleMessage objectForKey:@"enddate"]];
    dateLabel.font = [UIFont systemFontOfSize:14];
    dateLabel.textColor = [UIColor lightGrayColor];
    [cell.contentView addSubview:dateLabel];
    [dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lockNameLabel).with.offset(18);
        make.left.equalTo(icon).with.offset(40);
        make.height.mas_equalTo(35);
        make.right.mas_equalTo(-10);
    }];
    //留言
    UILabel *messageLabel = [[UILabel alloc]init];
    messageLabel.text = [singleMessage objectForKey:@"message"];
    messageLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    messageLabel.numberOfLines = 0;
    messageLabel.font = [UIFont systemFontOfSize:13];
    messageLabel.textColor = [UIColor lightGrayColor];
    [cell.contentView addSubview:messageLabel];
    [messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(dateLabel).with.offset(35);
        make.left.equalTo(icon).with.offset(40);
        make.right.mas_equalTo(-10);
        make.bottom.mas_equalTo(-5);
    }];
    //过期申请不可点击
    if(status.integerValue != 0 && status.integerValue != 3){
        cell.backgroundColor = RGB_UI_COLOR(240, 240, 230);
        cell.userInteractionEnabled = NO;
    }else{
        cell.backgroundColor = [UIColor clearColor];
    }
    //标示信息
    UILabel *statusLabel = [[UILabel alloc]init];
    statusLabel.numberOfLines = 0;
    statusLabel.font = [UIFont systemFontOfSize:17];
    [cell.contentView addSubview:statusLabel];
    [statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(30);
        make.top.equalTo(icon).with.offset(40);
        make.left.mas_equalTo(20);
    }];
    if(status.integerValue == 1){//同意
        statusLabel.text = @"已同意";
        statusLabel.textColor = RGB_UI_COLOR(102, 255, 153);
    }else if (status.integerValue == 2){//拒绝
        statusLabel.text = @"已拒绝";
        statusLabel.textColor = RGB_UI_COLOR(255, 102, 102);
    }else if (status.integerValue == 4 || status.integerValue == 5){//过期
        statusLabel.text = @"已过期";
        statusLabel.textColor = RGB_UI_COLOR(255, 242, 0);
    }else if (status.integerValue == 6){
        statusLabel.text = @"已撤消";
        statusLabel.textColor = RGB_UI_COLOR(230, 145, 56);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(nonnull NSIndexPath *)indexPath{
    NSLog(@"点击了详细按钮");
    NSDictionary *dic = self.allMessageInfor[indexPath.row];
    GUAAlertView *v = [GUAAlertView alertViewWithTitle:@""
                                               message:[NSString stringWithFormat:@"  %@\n\n  申请时间:%@",[dic objectForKey:@"message"],[dic objectForKey:@"regdate"]]
                                           buttonTitle:@"知道了"
                                   buttonTouchedAction:^{
                                       NSLog(@"button touched");
                                   } dismissAction:^{
                                       NSLog(@"dismiss");
                                   }];
    [v show];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *singleDic = self.allMessageInfor[indexPath.row];
    NSString *type = [singleDic objectForKey:@"type"];
    NSMutableArray *lockInfor = [NSMutableArray array];
    if(type.integerValue == 1 || type.integerValue == 2){
        //获取该钥匙串的详情
        [KLHelp showHUDAddedTo:self.view animated:YES];
        [KLHttpAPI requestAllLocksOfBrunchWithID:[singleDic objectForKey:@"id"] type:[singleDic objectForKey:@"type"] completionHandler:^(MKNetworkOperation *operation) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
            if(isSuccess.integerValue == 1){
                NSArray *groupDetailArr = [operation.responseJSON objectForKey:@"infor"];
                if(type.integerValue == 2){
                    for (NSDictionary *dic in groupDetailArr) {
                        NSString *lock_id = [dic objectForKey:@"lock_id"];
                        NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
                        [mutableDic setObject:lock_id forKey:@"lock_id"];
                        [mutableDic setObject:@"" forKey:@"rsa"];
                        [mutableDic setObject:@"" forKey:@"aes"];
                        [lockInfor addObject:mutableDic];
                    }
                }else{
                    for (NSDictionary *dic in groupDetailArr) {
                        NSString *lock_id = [dic objectForKey:@"lock_id"];
                        NSString *userAesKey = [KLHelp getUserSixTeenRandomAESKey];
                        NSString *rsaKey = [KLHelp getLockRSAPublicKeyWithLockName:[dic objectForKey:@"uname"]];
                        if(rsaKey.length == 0){
                            [KLHelp showTextHUDforView:self.view text:@"公钥丢失，请重新扫描二维码！"];
                            return ;
                        }
                        NSData *packageChildKey = [BuleFuction packChildkeyToData:rsaKey mobileStr:[singleDic objectForKey:@"applymobile"] startTime:@"000000000000" endTime:@"000000000000" commondCode:@"0" userAESKey:userAesKey];
                        rsaKey = [packageChildKey convertDataToHexStr:packageChildKey];
                        NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
                        [mutableDic setObject:lock_id forKey:@"lock_id"];
                        [mutableDic setObject:rsaKey forKey:@"rsa"];
                        [mutableDic setObject:userAesKey forKey:@"aes"];
                        [lockInfor addObject:mutableDic];
                    }
                }
                UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"是否同意申请" cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
                    [self sendSingleKey:singleDic status:@"3" type:[singleDic objectForKey:@"type"] lockInfor:lockInfor];
                }] destructiveButtonItem:nil otherButtonItems:[RIButtonItem itemWithLabel:@"同意" action:^{
                    [self sendSingleKey:singleDic status:@"1" type:[singleDic objectForKey:@"type"] lockInfor:lockInfor];
                }], [RIButtonItem itemWithLabel:@"拒绝" action:^{
                    [self sendSingleKey:singleDic status:@"2" type:[singleDic objectForKey:@"type"] lockInfor:lockInfor];
                }],nil];
                [actionSheet showInView:self.view];
            }
        } errorHandler:^(NSString *error) {
        }];
        
    }else{
        UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"是否同意申请" cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
            [self sendSingleKey:singleDic status:@"3" type:[singleDic objectForKey:@"type"] lockInfor:lockInfor];
        }] destructiveButtonItem:nil otherButtonItems:[RIButtonItem itemWithLabel:@"同意" action:^{
            [self sendSingleKey:singleDic status:@"1" type:[singleDic objectForKey:@"type"] lockInfor:lockInfor];
        }], [RIButtonItem itemWithLabel:@"拒绝" action:^{
            [self sendSingleKey:singleDic status:@"2" type:[singleDic objectForKey:@"type"] lockInfor:lockInfor];
        }],nil];
        [actionSheet showInView:self.view];
    
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [KLHelp showHUDAddedTo:self.view animated:YES];
    NSDictionary *singleMessageDic = self.allMessageInfor[indexPath.row];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [KLHttpAPI requestRemoveApplyKeyHidtoryWithNews_id:[singleMessageDic objectForKey:@"id"] completionHandler:^(MKNetworkOperation *operation) {
            NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
            if(isSuccess.integerValue == 1){
                [self refreshMessageList];
            }
        } errorHandler:^(NSString *error) {
        }];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

//发送单把钥匙
-(void)sendSingleKey:(NSDictionary *)singleMessage status:(NSString *)status type:(NSString *)type lockInfor:(NSMutableArray *)lockInfo{
    NSString *key_str;
    NSString *AESkey;
    if(type.integerValue == 0){
        if(status.integerValue == 1){
            //获取锁公钥
            NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
            NSDictionary *publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
            NSString *codeStr = [publicKeysDic objectForKey:[singleMessage objectForKey:@"uname"]];
            if(codeStr.length == 0){
                [KLHelp showTextHUDforView:self.view text:@"锁公钥丢失!"];
                return ;
            }
            //服务器时间
            NSString *startDate = [singleMessage objectForKey:@"startdate"];
            NSString *endDate = [singleMessage objectForKey:@"enddate"];
            //给锁的时间
            NSString *starDateToLock = [startDate substringFromIndex:2];
            starDateToLock = [starDateToLock stringByReplacingOccurrencesOfString:@" " withString:@""];
            starDateToLock = [starDateToLock stringByReplacingOccurrencesOfString:@"-" withString:@""];
            starDateToLock = [starDateToLock stringByReplacingOccurrencesOfString:@":" withString:@""];
            NSString *endDateToLock = [endDate substringFromIndex:2];
            endDateToLock = [endDateToLock stringByReplacingOccurrencesOfString:@" " withString:@""];
            endDateToLock = [endDateToLock stringByReplacingOccurrencesOfString:@"-" withString:@""];
            endDateToLock = [endDateToLock stringByReplacingOccurrencesOfString:@":" withString:@""];
            //给锁的aeskey
            AESkey = [KLHelp getUserSixTeenRandomAESKey];
            
            NSData *packageChildKey = [BuleFuction packChildkeyToData:codeStr mobileStr:[singleMessage objectForKey:@"applymobile"] startTime:starDateToLock endTime:endDateToLock commondCode:@"0" userAESKey:AESkey];
            key_str = [packageChildKey convertDataToHexStr:packageChildKey];
            [KLHelp showTextHUDforView:self.view text:@"正在下发钥匙..."];
        }else{
            key_str = @"";
            AESkey = @"";
            if(status.integerValue == 2){
                [KLHelp showHUDAddedTo:self.view animated:YES];
            }
        }

        NSLog(@"打包子钥匙后的数据包的字符串:%@",key_str);
        [KLHttpAPI requestMasterIsAgreedWithKey_str:key_str AESkey:AESkey power:@"01" Command_code:@"a1" updatetime:@"0" news_id:[singleMessage objectForKey:@"id"] status:status completionHandler:^(MKNetworkOperation *operation) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            NSLog(@"operation:%@",operation.responseString);
            NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
            if(isSuccess.integerValue == 1){
                [self refreshMessageList];
            }
            if(status.integerValue != 3){
                [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
            }
        } errorHandler:^(NSString *error) {
            [KLHelp showTextHUDforView:self.view text:error];
        }];
    }else{
        //是否同意钥匙串申请，rsa_data和aes_data传入数组
        [KLHttpAPI agreeTheKeyBrunchApplyedWithLockInfo:lockInfo news_id:[singleMessage objectForKey:@"id"] power:@"01" Command_code:@"a1" updatetime:@"0" status:[singleMessage objectForKey:@"status"] completionHandler:^(MKNetworkOperation *operation) {
            NSLog(@"同意/取消钥匙串返回数据:%@",operation.responseString);
            
        } errorHandler:^(NSString *error) {
            
        }];
    }
}

-(void)refreshMessageList{
    [KLHttpAPI requestApplyKeyMessageWithCompletionHandler:^(MKNetworkOperation *operation) {
        [self.tableView.mj_header endRefreshing];
        NSLog(@"获取申请消息列表:%@",operation.responseString);
        NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            self.allMessageInfor = [NSArray array];
            NSArray *emptDic = [operation.responseJSON objectForKey:@"infor"];
            if(![emptDic isKindOfClass:[NSNull class]] && emptDic.count > 0){
                [KLHelp removeImgViewAndNoticeLabel];
                self.allMessageInfor = emptDic;
            }else{
                [KLHelp setNoDateImageWithView:self.tableView type:0];
            }
            [self.tableView reloadData];
        }
    } errorHandler:^(NSString *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

-(BOOL)prefersStatusBarHidden{
    return YES;
}
@end
